package com.msw.design.proxy.dynamic;

import com.msw.design.proxy.statics.RealSubject;
import com.msw.design.proxy.statics.Subject;
import sun.misc.ProxyGenerator;

import java.io.FileOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * Created by minshiwu on 2017/6/4.
 */
public class Client {

    /**
     * 动态代理的Client端
     *
     * @param args
     */
    public static void main(String[] args) {
        RealSubject realSubject = new RealSubject();

        InvocationHandler handler = new DynamicSubject(realSubject);

        // jdk生产的代理对象,等同于static代理模式的proxySubject
        Subject subject = (Subject) Proxy.newProxyInstance(realSubject.getClass().getClassLoader(),
                realSubject.getClass().getInterfaces(), handler);
        System.err.println(subject.getClass().getTypeName());
        subject.request("world");

//        createProxyClassFile();
    }

    /**
     * 将jdk生产的代理类源码打印出来
     *
     */
    public static void createProxyClassFile()
    {
        String name = "ProxySubject";
        byte[] data = ProxyGenerator.generateProxyClass( name, new Class[] { Subject.class } );
        try
        {
            FileOutputStream out = new FileOutputStream( name + ".class" );
            out.write( data );
            out.close();
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }
    }

}
